package net.akkz.urlMapping;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UrlMappingWithPermissionClass implements Filter
{
	String packageName;
	String errorPage;

	@Override
	public void destroy()
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException
	{
		try
		{
			String path = ((HttpServletRequest) request).getServletPath();
			
			int servletIndex = path.lastIndexOf('/');
			int dollIndex = path.lastIndexOf('.');
			
			String servlet = null;
			String method = null;
			String url = null;
			
			if(dollIndex == -1)
			{
				servlet = path.substring(servletIndex+1);
				method = "";
				url = path;
			}
			else
			{
				servlet = path.substring(servletIndex+1, dollIndex);
				method = path.substring(dollIndex + 1);
				url = path.substring(0, dollIndex);
			}
			
			String permission = (String) Class.forName(this.packageName + servlet).getField("permission").get(String.class);
			String cPermission =  (String) ((HttpServletRequest) request).getSession().getAttribute("permission");

			if(cPermission != null && permission != null)
			{
				for(String s : cPermission.split(","))
				{
					if(permission.contains(s))
					{
						request.setAttribute("method", method);
						request.getRequestDispatcher(url).forward(request, response);
						
						return;
					}
				}
			}
		}
		catch (ClassNotFoundException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e)
		{
			e.printStackTrace();
			
			throw new ServletException(e);
		}
		catch (StringIndexOutOfBoundsException e)
		{
			e.printStackTrace();
			
			throw new ServletException(e);
		}
		
		((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath() + errorPage);
	}

	@Override
	public void init(FilterConfig filter) throws ServletException
	{
		this.packageName = (String)filter.getInitParameter("packageName");
		this.errorPage = (String)filter.getInitParameter("errorPage");
		
		if(this.packageName == null || this.errorPage == null)
			throw new ServletException();
	}

}
